<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理-图书馆座位预约管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
            overflow-x: hidden;
        }

        /* 左侧导航栏样式 */
        .sidebar {
            width: 250px;
            background: #1a2a6c;
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            transition: width 0.3s ease;
            z-index: 1000;
        }

        .sidebar.collapsed {
            width: 70px;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
        }

        .logo i {
            font-size: 1.5rem;
            min-width: 24px;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
        }

        .nav-item {
            margin: 5px 0;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
            white-space: nowrap;
            overflow: hidden;
        }

        .nav-link:hover, .nav-item.active .nav-link {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .nav-link i {
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            transition: margin-left 0.3s ease;
            width: calc(100vw - 250px);
            min-height: 100vh;
        }

        .main-content.expanded {
            margin-left: 70px;
            width: calc(100vw - 70px);
        }

        /* 顶部导航栏 */
        .top-navbar {
            background-color: white;
            padding: 12px 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .navbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #1a2a6c;
            padding: 5px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .menu-toggle:hover {
            background-color: #f0f0f0;
        }

        .page-title {
            color: #1a2a6c;
            font-size: 1.4rem;
            font-weight: 600;
        }

        .navbar-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            padding: 8px 35px 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }

        .search-box i {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #888;
        }

        .notification {
            position: relative;
            cursor: pointer;
        }

        .notification .badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #e74c3c;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-profile img {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
            background-color: #1a73e8;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        /* 用户管理内容区域 */
        .user-management {
            padding: 20px;
            flex: 1;
            width: 100%;
            overflow-x: hidden;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-item label {
            font-weight: 500;
            white-space: nowrap;
            font-size: 14px;
        }

        .form-control {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
            height: 36px;
            font-size: 14px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            transition: all 0.3s;
            height: 36px;
            font-size: 14px;
        }

        .btn-primary {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        .btn-primary:hover {
            background: #0d62d9;
            border-color: #0d62d9;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid #ddd;
            color: #1a73e8;
        }

        .btn-outline:hover {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        /* 批量操作区域 */
        .batch-actions {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .batch-info {
            font-size: 14px;
            color: #666;
        }

        .batch-buttons {
            display: flex;
            gap: 10px;
        }

        .btn-batch {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            font-weight: 500;
            transition: all 0.3s;
            height: 32px;
            font-size: 13px;
        }

        .btn-batch.freeze {
            color: #f39c12;
            border-color: #f39c12;
        }

        .btn-batch.freeze:hover {
            background: #f39c12;
            color: white;
        }

        .btn-batch.unfreeze {
            color: #2ecc71;
            border-color: #2ecc71;
        }

        .btn-batch.unfreeze:hover {
            background: #2ecc71;
            color: white;
        }

        .btn-batch.delete {
            color: #e74c3c;
            border-color: #e74c3c;
        }

        .btn-batch.delete:hover {
            background: #e74c3c;
            color: white;
        }

        /* 统计卡片样式 */
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 18px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
        }

        .stat-card:nth-child(1) .stat-icon {
            background: rgba(26, 115, 232, 0.1);
            color: #1a73e8;
        }

        .stat-card:nth-child(2) .stat-icon {
            background: rgba(46, 204, 113, 0.1);
            color: #2ecc71;
        }

        .stat-card:nth-child(3) .stat-icon {
            background: rgba(241, 196, 15, 0.1);
            color: #f39c12;
        }

        .stat-card:nth-child(4) .stat-icon {
            background: rgba(231, 76, 60, 0.1);
            color: #e74c3c;
        }

        .stat-content {
            flex: 1;
        }

        .stat-value {
            font-size: 22px;
            font-weight: bold;
            color: #1a2a6c;
        }

        .stat-label {
            color: #7f8c8d;
            font-size: 13px;
        }

        .stat-trend {
            font-size: 13px;
            font-weight: 500;
        }

        .stat-trend.positive {
            color: #2ecc71;
        }

        .stat-trend.negative {
            color: #e74c3c;
        }

        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            width: 100%;
            overflow: hidden;
        }

        .card-header {
            padding: 18px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a2a6c;
        }

        .table-info {
            color: #7f8c8d;
            font-size: 13px;
        }

        .table-container {
            overflow-x: auto;
            width: 100%;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 700px;
        }

        .data-table th, .data-table td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }

        .data-table th {
            background: #1a2a6c;
            color: white;
            font-weight: 600;
            font-size: 14px;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status.active {
            background: rgba(46, 204, 113, 0.2);
            color: #27ae60;
        }

        .status.frozen {
            background: rgba(243, 156, 18, 0.2);
            color: #f39c12;
        }

        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            margin: 0 2px;
            border-radius: 4px;
            transition: all 0.3s;
            font-size: 14px;
        }

        .action-btn.view {
            color: #3498db;
        }

        .action-btn.view:hover {
            background: rgba(52, 152, 219, 0.1);
        }

        .action-btn.edit {
            color: #2ecc71;
        }

        .action-btn.edit:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .action-btn.freeze {
            color: #f39c12;
        }

        .action-btn.freeze:hover {
            background: rgba(243, 156, 18, 0.1);
        }

        .action-btn.unfreeze {
            color: #2ecc71;
        }

        .action-btn.unfreeze:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .action-btn.delete {
            color: #e74c3c;
        }

        .action-btn.delete:hover {
            background: rgba(231, 76, 60, 0.1);
        }

        /* 冻结状态特殊样式 */
        .frozen-user {
            background-color: rgba(243, 156, 18, 0.05) !important;
        }

        .frozen-user:hover {
            background-color: rgba(243, 156, 18, 0.1) !important;
        }

        .frozen-icon {
            color: #f39c12;
            margin-right: 5px;
            font-size: 14px;
        }

        /* 禁用按钮样式 */
        .action-btn.disabled {
            color: #ccc !important;
            cursor: not-allowed;
            opacity: 0.5;
        }

        .action-btn.disabled:hover {
            background: none !important;
        }

        .btn-batch.disabled {
            color: #ccc !important;
            border-color: #ccc !important;
            cursor: not-allowed;
            opacity: 0.5;
        }

        .btn-batch.disabled:hover {
            background: transparent !important;
            color: #ccc !important;
        }

        .card-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pagination ul {
            display: flex;
            list-style: none;
            gap: 5px;
        }

        .pagination a {
            display: block;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #1a73e8;
            transition: all 0.3s;
            font-size: 14px;
        }

        .pagination a.active, .pagination a:hover {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        .pagination a.disabled {
            color: #ccc;
            cursor: not-allowed;
            pointer-events: none;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            width: 500px;
            max-width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #1a2a6c;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #7f8c8d;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #333;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-group textarea {
            min-height: 80px;
            resize: vertical;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .stats-cards {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 70px;
            }

            .sidebar:not(.collapsed) .logo span,
            .sidebar:not(.collapsed) .nav-link span {
                display: none;
            }

            .main-content {
                margin-left: 70px;
                width: calc(100vw - 70px);
            }

            .toolbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-container {
                width: 100%;
            }

            .action-buttons {
                width: 100%;
                justify-content: flex-start;
            }

            .stats-cards {
                grid-template-columns: 1fr;
            }

            .search-box input {
                width: 200px;
            }

            .batch-actions {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
        }

        @media (max-width: 576px) {
            .top-navbar {
                padding: 10px 15px;
            }

            .user-management {
                padding: 15px;
            }

            .search-box input {
                width: 150px;
            }

            .filter-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }

            .form-control {
                min-width: 120px;
            }

            .card-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .navbar-right {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>

<div class="admin-container">
    <!-- 左侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <h1 class="logo">
                <i class="fa fa-book"></i>
                <span>图书馆座位预约管理系统</span>
            </h1>
        </div>
        <nav class="sidebar-nav">
            <ul>
                <li class="nav-item">
                    <a href="index.html" class="nav-link">
                        <i class="fa fa-home"></i>
                        <span>首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="seat-management1.html" class="nav-link">
                        <i class="fa fa-th-large"></i>
                        <span>座位管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="booking-management.html" class="nav-link">
                        <i class="fa fa-calendar-check-o"></i>
                        <span>预约管理</span>
                    </a>
                </li>
                <li class="nav-item active">
                    <a href="user-management1.html" class="nav-link">
                        <i class="fa fa-users"></i>
                        <span>用户管理</span>
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
        <!-- 顶部导航栏区域 -->
        <header class="top-navbar">
            <div class="navbar-left">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fa fa-bars"></i>
                </button>
                <h2 class="page-title">用户管理</h2>
            </div>
            <div class="navbar-right">
                <div class="search-box">
                    <input type="text" placeholder="搜索用户..." id="searchInput">
                    <i class="fa fa-search"></i>
                </div>
                <div class="user-profile">
                    <img src="manager.png" alt="管理员头像">
                    <span>管理员</span>
                </div>
            </div>
        </header>

        <!-- 用户管理内容 -->
        <div class="user-management">
            <!-- 工具栏 -->
            <div class="toolbar">
                <div class="filter-container">
                    <div class="filter-item">
                        <label>用户状态:</label>
                        <select class="form-control" id="statusFilter">
                            <option value="all">全部状态</option>
                            <option value="active">正常</option>
                            <option value="frozen">冻结</option>
                        </select>
                    </div>
                </div>
                <div class="action-buttons">
                    <button class="btn btn-primary" id="addUserBtn">
                        <i class="fa fa-plus"></i> 新增用户
                    </button>
                    <button class="btn btn-outline" id="refreshBtn">
                        <i class="fa fa-refresh"></i> 刷新
                    </button>
                </div>
            </div>

            <!-- 用户表格 -->
            <div class="card">
                <div class="card-header">
                    <h3>用户列表</h3>
                    <div class="table-info">
                        <span id="userCount">正在加载用户数据...</span>
                    </div>
                </div>

                <!-- 批量操作区域 -->
                <div class="batch-actions" id="batchActions" style="display: none;">
                    <div class="batch-info" id="batchInfo">已选择 0 个用户</div>
                    <div class="batch-buttons">
                        <button class="btn-batch freeze" id="batchFreeze">
                            <i class="fa fa-snowflake"></i> 批量冻结
                        </button>
                        <button class="btn-batch unfreeze" id="batchUnfreeze">
                            <i class="fa fa-temperature-high"></i> 批量解冻
                        </button>
                        <button class="btn-batch delete" id="batchDelete">
                            <i class="fa fa-trash"></i> 批量删除
                        </button>
                    </div>
                </div>

                <div class="table-container">
                    <table class="data-table" id="userTable">
                        <thead>
                        <tr>
                            <th>序号</th>
                            <th>用户名</th>
                            <th>密码</th>
                            <th>邮箱</th>
                            <th>手机号</th>
                            <th>违约次数</th>
                            <th>状态</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="userTableBody">
                        <!-- 用户数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
                <div class="card-footer">
                    <div class="pagination">
                        <ul>
                            <li><a href="#" id="prevPage">上一页</a></li>
                            <li><a href="#" class="active">1</a></li>
                            <li><a href="#" id="nextPage">下一页</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 新增/编辑用户模态框 -->
<div class="modal" id="userModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">新增用户</h3>
            <button class="modal-close" id="modalClose">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="modal-body">
            <form id="userForm">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password">
                </div>
                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" name="email" required>
                </div>
                <div class="form-group">
                    <label for="phone">手机号</label>
                    <input type="tel" id="phone" name="phone" required>
                </div>
                <div class="form-group">
                    <label for="grade">年级</label>
                    <input type="text" id="grade" name="grade">
                </div>
                <div class="form-group">
                    <label for="education">学历</label>
                    <input type="text" id="education" name="education">
                </div>
                <div class="form-group">
                    <label for="college">学院</label>
                    <input type="text" id="college" name="college">
                </div>
                <div class="form-group">
                    <label for="major">专业</label>
                    <input type="text" id="major" name="major">
                </div>
                <div class="form-group">
                    <label for="violationCount">违约次数</label>
                    <input type="number" id="violationCount" name="violationCount" min="0" value="0">
                </div>
                <div class="form-group">
                    <label for="userStatus">状态</label>
                    <select id="userStatus" name="userStatus" required>
                        <option value="active">正常</option>
                        <option value="frozen">冻结</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="userNotes">备注</label>
                    <textarea id="userNotes" name="userNotes"></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="modalCancel">取消</button>
            <button class="btn btn-primary" id="modalSave">保存</button>
        </div>
    </div>
</div>

<!-- 用户详情模态框 -->
<div class="modal" id="userDetailModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>用户详情</h3>
            <button class="modal-close" id="detailModalClose">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="modal-body">
            <div id="userDetailContent">
                <!-- 用户详情将通过JavaScript动态生成 -->
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" id="detailModalCloseBtn">关闭</button>
        </div>
    </div>
</div>

<script>
    // 用户数据 - 从后端API获取
    let users = [];

    // 当前编辑的用户ID
    let currentEditUserId = null;

    // 基础API URL - 根据实际部署情况修改
    const API_BASE_URL = 'http://localhost:8080/api/user';

    // 菜单切换功能
    const menuToggle = document.getElementById('menuToggle');
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');

    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        });
    }

    // 从后端API获取所有用户数据
    async function fetchAllUsers() {
        try {
            const response = await fetch(`${API_BASE_URL}/get-all`);
            if (!response.ok) {
                throw new Error('获取用户数据失败');
            }
            const userList = await response.json();

            console.log(userList)

            // 转换数据格式以匹配前端显示需求
            return userList.map((user,index) => ({
                index: index+1,
                name: user.username,
                password: user.password,
                email: user.email || '未设置',
                phone: user.phone || '未设置',
                violationCount: user.violationCount || 0, // 添加违约次数
                status: user.status || 'active',
                conments: user.conments || '无',
                notes: user.notes || ''
            }));
        } catch (error) {
            console.error('Error fetching users:', error);
            alert('获取用户数据失败: ' + error.message);
            return [];
        }
    }

    // 渲染用户表格
    async function renderUserTable(userList = users) {
        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = '';

        if (userList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无用户数据</td></tr>';
            document.getElementById('userCount').textContent = '共 0 个用户';
            return;
        }

        userList.forEach(user => {
            const statusText = getStatusText(user.status);
            const statusClass = getStatusClass(user.status);
            const isFrozen = user.status === 'frozen';
            const isActive = user.status === 'active';

            const row = document.createElement('tr');
            if (isFrozen) {
                row.classList.add('frozen-user');
            }

            row.innerHTML = `
                <td>${user.index}</td>
                <td>${user.name}</td>
                <td>${user.password}</td>
                <td>${user.email}</td>
                <td>${user.phone}</td>
                <td>${user.violationCount || 0}</td> <!-- 新增违约次数显示 -->
                <td><span class="status ${statusClass}">${statusText}</span></td>
                <td>${user.conments || '无'}</td>
                <td>
                    <button class="action-btn view" data-id="${user.name}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                    <button class="action-btn edit" data-id="${user.name}" title="编辑用户">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="action-btn freeze ${!isActive ? 'disabled' : ''}" data-id="${user.name}" title="${isActive ? '冻结用户' : '当前状态无法冻结'}" ${!isActive ? 'disabled' : ''}>
                        <i class="fa fa-snowflake-o"></i>
                    </button>
                    <button class="action-btn unfreeze ${!isFrozen ? 'disabled' : ''}" data-id="${user.name}" title="${isFrozen ? '解冻用户' : '当前状态无法解冻'}" ${!isFrozen ? 'disabled' : ''}>
                        <i class="fa fa-sun-o"></i>
                    </button>
                    <button class="action-btn delete" data-id="${user.name}" title="删除用户">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            `;

            tbody.appendChild(row);
        });

        // 更新用户数量
        document.getElementById('userCount').textContent = `共 ${userList.length} 个用户`;

        // 重新绑定事件
        bindTableEvents();
        setupBatchOperations();
    }

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'active': '正常',
            'frozen': '冻结'
        };
        return statusMap[status] || '未知';
    }

    // 获取状态类名
    function getStatusClass(status) {
        const classMap = {
            'active': 'active',
            'frozen': 'frozen'
        };
        return classMap[status] || 'frozen';
    }

    // 绑定表格事件
    function bindTableEvents() {
        // 查看用户详情
        document.querySelectorAll('.action-btn.view').forEach(btn => {
            btn.addEventListener('click', function() {
                const username = this.getAttribute('data-id');
                console.log('查看用户详情:', username);
                showUserDetail(username);
            });
        });

        // 编辑用户
        document.querySelectorAll('.action-btn.edit').forEach(btn => {
            btn.addEventListener('click', function() {
                const username = this.getAttribute('data-id');
                editUser(username);
            });
        });

        // 冻结用户
        document.querySelectorAll('.action-btn.freeze:not(.disabled)').forEach(btn => {
            btn.addEventListener('click', function() {
                const username = this.getAttribute('data-id');
                freezeUser(username);
            });
        });

        // 解冻用户
        document.querySelectorAll('.action-btn.unfreeze:not(.disabled)').forEach(btn => {
            btn.addEventListener('click', function() {
                const username = this.getAttribute('data-id');
                unfreezeUser(username);
            });
        });

        // 删除用户
        document.querySelectorAll('.action-btn.delete').forEach(btn => {
            btn.addEventListener('click', function() {
                const username = this.getAttribute('data-id');
                deleteUser(username);
            });
        });
    }

    // 显示用户详情
    async function showUserDetail(username) {
        try {
            console.log('获取用户详情1:', username);
            const response = await fetch(`${API_BASE_URL}/get-info?username=${username}`);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status} - ${response.statusText}`);
            }
            const user = await response.json();

            const detailContent = document.getElementById('userDetailContent');
            detailContent.innerHTML = `
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div><strong>用户名:</strong> ${user.username}</div>
                <div><strong>邮箱:</strong> ${user.email || '未设置'}</div>
                <div><strong>手机号:</strong> ${user.phone || '未设置'}</div>
                <div><strong>年级:</strong> ${user.grade || '未设置'}</div>
                <div><strong>学历:</strong> ${user.education || '未设置'}</div>
                <div><strong>学院:</strong> ${user.college || '未设置'}</div>
                <div><strong>专业:</strong> ${user.major || '未设置'}</div>
                <div><strong>违约次数:</strong> ${user.violationCount || 0}</div>
                <div><strong>状态:</strong> <span class="status ${getStatusClass(user.status || 'active')}">${getStatusText(user.status || 'active')}</span></div>
            </div>
            <div style="margin-top: 15px;">
                <strong>备注:</strong>
                ${user.conments || "无"}
            </div>
        `;

            document.getElementById('userDetailModal').classList.add('show');
        } catch (error) {
            console.error('Error fetching user details:', error);
            alert('获取用户详情失败: ' + error.message);
        }
    }

    // 编辑用户
    async function editUser(username) {
        try {
            console.log('编辑用户:', username);
            const resp = await fetch(`${API_BASE_URL}/get-info?username=${username}`);
            if (!resp.ok) throw new Error('获取用户信息失败');
            const user = await resp.json();
            console.log('用户信息:', user);

            // 记住当前主键
            currentEditUserId = username;

            // 填充表单
            document.getElementById('modalTitle').textContent = '编辑用户';
            document.getElementById('username').value       = user.username;
            document.getElementById('username').disabled    = true;
            document.getElementById('password').value       = '';
            document.getElementById('password').placeholder = '留空表示不修改密码';
            document.getElementById('email').value          = user.email   || '';
            document.getElementById('phone').value          = user.phone   || '';
            document.getElementById('grade').value          = user.grade   || '';
            document.getElementById('education').value      = user.education || '';
            document.getElementById('college').value        = user.college || '';
            document.getElementById('major').value          = user.major   || '';
            document.getElementById('violationCount').value = user.violationCount || 0;
            document.getElementById('userStatus').value     = user.status  || 'active';
            document.getElementById('userNotes').value      = user.notes   || '';

            document.getElementById('userModal').classList.add('show');
        } catch (e) {
            console.error(e);
            alert('获取用户详情失败：' + e.message);
        }
    }

    // 新增用户
    function addUser() {
        currentEditUserId = null;
        document.getElementById('modalTitle').textContent = '新增用户';

        // 清空表单
        document.getElementById('userForm').reset();
        document.getElementById('username').disabled = false; // 新增时允许输入用户名

        document.getElementById('userModal').classList.add('show');
    }

    // 保存用户
    async function saveUser() {
        const formData = {
            username: document.getElementById('username').value,
            password: document.getElementById('password').value,
            email: document.getElementById('email').value,
            phone: document.getElementById('phone').value,
            grade: document.getElementById('grade').value,
            education: document.getElementById('education').value,
            college: document.getElementById('college').value,
            major: document.getElementById('major').value,
            status: document.getElementById('userStatus').value,
            notes: document.getElementById('userNotes').value,
            violationCount: 0
        };

        // 如果有密码字段且不为空，则添加密码
        const password = document.getElementById('password').value;
        if (password) {
            formData.password = password;
        }

        try {
            let response;
            if (currentEditUserId) {
                // 编辑现有用户 - 使用PATCH请求
                const updateData = {};
                if (formData.email) updateData.email = formData.email;
                if (formData.phone) updateData.phone = formData.phone;
                if (formData.grade) updateData.grade = formData.grade;
                if (formData.education) updateData.education = formData.education;
                if (formData.college) updateData.college = formData.college;
                if (formData.major) updateData.major = formData.major;
                if (formData.status) updateData.status = formData.status;
                if (formData.notes) updateData.notes = formData.notes;

                response = await fetch(`${API_BASE_URL}/update-info?username=${currentEditUserId}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updateData)
                });
            } else {
                // 新增用户
                response = await fetch(`${API_BASE_URL}/add`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
            }

            const result = await response.json();

            if (result.success) {
                // 重新加载用户列表
                await loadUsers();
                closeModal('userModal');
                alert(currentEditUserId ? '用户信息已更新' : '用户已成功添加');
            } else {
                throw new Error(result.message || '操作失败');
            }
        } catch (error) {
            console.error('Error saving user:', error);
            alert('保存用户失败: ' + error.message);
        }
    }

    // 冻结用户（POST 无 body）
    async function freezeUser(username) {
        if (!confirm('确定要冻结此用户吗？')) return;
        try {
            const resp = await fetch(`${API_BASE_URL}/freeze/${username}`, {
                method: 'POST'   // 后端要求 POST，无参数
            });
            const result = await resp.json();

            if (result.success) {
                alert('用户已冻结');
                await loadUsers(); // 刷新列表
            } else {
                alert('冻结失败：' + result.message);
            }
        } catch (e) {
            console.error(e);
            alert('冻结出错：' + e.message);
        }
    }

    // 解冻用户（POST 无 body）
    async function unfreezeUser(username) {
        if (!confirm('确定要解冻此用户吗？')) return;
        try {
            const resp = await fetch(`${API_BASE_URL}/unfreeze/${username}`, {
                method: 'POST'   // 后端要求 POST，无参数
            });
            const result = await resp.json();

            if (result.success) {
                alert('用户已解冻');
                await loadUsers(); // 刷新列表
            } else {
                alert('解冻失败：' + result.message);
            }
        } catch (e) {
            console.error(e);
            alert('解冻出错：' + e.message);
        }
    }

    // 删除用户
    async function deleteUser(username) {
        if (confirm('确定要删除此用户吗？此操作不可恢复！')) {
            try {
                const response = await fetch(`${API_BASE_URL}/delete/${username}`, {
                    method: 'DELETE'
                });

                const result = await response.json();
                if (result.success) {
                    await loadUsers();
                    alert('用户已删除');
                } else {
                    throw new Error(result.message || '删除失败');
                }
            } catch (error) {
                console.error('Error deleting user:', error);
                alert('删除用户失败: ' + error.message);
            }
        }
    }

    // 关闭模态框
    function closeModal(modalId) {
        document.getElementById(modalId).classList.remove('show');
    }

    // 搜索功能
    function setupSearch() {
        const searchInput = document.getElementById('searchInput');
        const statusFilter = document.getElementById('statusFilter');

        function filterUsers() {
            const searchTerm = searchInput.value.toLowerCase();
            const statusValue = statusFilter.value;

            const filteredUsers = users.filter(user => {
                // 搜索条件
                const matchesSearch = !searchTerm ||
                    user.name.toLowerCase().includes(searchTerm) ||
                    user.email.toLowerCase().includes(searchTerm);

                // 状态筛选
                const matchesStatus = statusValue === 'all' || user.status === statusValue;

                return matchesSearch && matchesStatus;
            });

            renderUserTable(filteredUsers);
        }

        searchInput.addEventListener('input', filterUsers);
        statusFilter.addEventListener('change', filterUsers);
    }

    // 批量操作功能
    function setupBatchOperations() {
        const batchActions = document.getElementById('batchActions');
        const batchInfo = document.getElementById('batchInfo');
        const batchFreezeBtn = document.getElementById('batchFreeze');
        const batchUnfreezeBtn = document.getElementById('batchUnfreeze');
        const batchDeleteBtn = document.getElementById('batchDelete');

        // 更新批量操作区域
        function updateBatchActions() {
            const checkedCount = 0; // 由于删除了选择框，这里设为0

            if (checkedCount > 0) {
                batchActions.style.display = 'flex';
                batchInfo.textContent = `已选择 ${checkedCount} 个用户`;

                // 更新批量按钮状态
                updateBatchButtonsState();
            } else {
                batchActions.style.display = 'none';
            }
        }

        // 更新批量按钮状态
        function updateBatchButtonsState() {
            const selectedIds = []; // 由于删除了选择框，这里设为空数组

            // 检查是否有可冻结的用户（状态为active）
            const hasActiveUsers = selectedIds.some(id => {
                const user = users.find(u => u.id === id);
                return user && user.status === 'active';
            });

            // 检查是否有可解冻的用户（状态为frozen）
            const hasFrozenUsers = selectedIds.some(id => {
                const user = users.find(u => u.id === id);
                return user && user.status === 'frozen';
            });

            // 更新按钮状态
            if (hasActiveUsers) {
                batchFreezeBtn.classList.remove('disabled');
                batchFreezeBtn.disabled = false;
            } else {
                batchFreezeBtn.classList.add('disabled');
                batchFreezeBtn.disabled = true;
            }

            if (hasFrozenUsers) {
                batchUnfreezeBtn.classList.remove('disabled');
                batchUnfreezeBtn.disabled = false;
            } else {
                batchUnfreezeBtn.classList.add('disabled');
                batchUnfreezeBtn.disabled = true;
            }

            // 删除按钮始终可用
            batchDeleteBtn.classList.remove('disabled');
            batchDeleteBtn.disabled = false;
        }

        // 批量操作按钮事件
        batchFreezeBtn.addEventListener('click', async function() {
            if (this.disabled) return;

            const selectedIds = []; // 由于删除了选择框，这里设为空数组
            const activeUsers = selectedIds.filter(id => {
                const user = users.find(u => u.id === id);
                return user && user.status === 'active';
            });

            if (activeUsers.length > 0) {
                if (confirm(`确定要冻结选中的 ${activeUsers.length} 个正常用户吗？`)) {
                    try {
                        for (const id of activeUsers) {
                            const updateData = { status: 'frozen' };
                            await fetch(`${API_BASE_URL}/update-info?username=${id}`, {
                                method: 'PATCH',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(updateData)
                            });
                        }
                        await loadUsers();
                        alert(`已成功冻结 ${activeUsers.length} 个用户`);
                    } catch (error) {
                        console.error('Error batch freezing users:', error);
                        alert('批量冻结用户失败: ' + error.message);
                    }
                }
            }
        });

        batchUnfreezeBtn.addEventListener('click', async function() {
            if (this.disabled) return;

            const selectedIds = []; // 由于删除了选择框，这里设为空数组
            const frozenUsers = selectedIds.filter(id => {
                const user = users.find(u => u.id === id);
                return user && user.status === 'frozen';
            });

            if (frozenUsers.length > 0) {
                if (confirm(`确定要解冻选中的 ${frozenUsers.length} 个冻结用户吗？`)) {
                    try {
                        for (const id of frozenUsers) {
                            const updateData = { status: 'active' };
                            await fetch(`${API_BASE_URL}/update-info?username=${id}`, {
                                method: 'PATCH',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(updateData)
                            });
                        }
                        await loadUsers();
                        alert(`已成功解冻 ${frozenUsers.length} 个用户`);
                    } catch (error) {
                        console.error('Error batch unfreezing users:', error);
                        alert('批量解冻用户失败: ' + error.message);
                    }
                }
            }
        });

        batchDeleteBtn.addEventListener('click', async function() {
            if (this.disabled) return;

            const selectedIds = []; // 由于删除了选择框，这里设为空数组
            if (selectedIds.length > 0) {
                if (confirm(`确定要删除选中的 ${selectedIds.length} 个用户吗？此操作不可恢复！`)) {
                    try {
                        for (const id of selectedIds) {
                            await fetch(`${API_BASE_URL}/delete/${id}`, {
                                method: 'DELETE'
                            });
                        }
                        await loadUsers();
                        alert(`已成功删除 ${selectedIds.length} 个用户`);
                    } catch (error) {
                        console.error('Error batch deleting users:', error);
                        alert('批量删除用户失败: ' + error.message);
                    }
                }
            }
        });
    }

    // 加载用户数据
    async function loadUsers() {
        users = await fetchAllUsers();
        renderUserTable(users);
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadUsers();
        setupSearch();

        // 新增用户按钮
        document.getElementById('addUserBtn').addEventListener('click', addUser);

        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', function() {
            loadUsers();
            document.getElementById('searchInput').value = '';
            document.getElementById('statusFilter').value = 'all';
        });

        // 模态框关闭
        document.getElementById('modalClose').addEventListener('click', function() {
            closeModal('userModal');
        });

        document.getElementById('modalCancel').addEventListener('click', function() {
            closeModal('userModal');
        });

        document.getElementById('detailModalClose').addEventListener('click', function() {
            closeModal('userDetailModal');
        });

        document.getElementById('detailModalCloseBtn').addEventListener('click', function() {
            closeModal('userDetailModal');
        });

        // 保存用户
        document.getElementById('modalSave').addEventListener('click', saveUser);

        // 点击模态框外部关闭
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('show');
                }
            });
        });
    });
</script>
</body>
</html>